using System;
using Microsoft.Build.Framework;
using System.Diagnostics;
using System.Collections.Generic;
using RunAllTestsInSolutionTask;

namespace NCoverTasks
{
    public class NCoverAllTestInSolution : RunAllTestsInSolution
    {
        [Required]
        public string NCoverConsole
        {
            get;
            set;
        }

        public string WorkingDirectory
        {
            get;
            set;
        }

        public override bool Execute()
        {
            return base.Execute();
        }

        override protected ProcessStartInfo CreateProcessStartInfo(IList<string> testdlls)
        {
            Console.WriteLine("NCOVER-------------");
            var processInfo = new ProcessStartInfo();
            if ( !String.IsNullOrEmpty(WorkingDirectory))
            {
                processInfo.WorkingDirectory = WorkingDirectory;
                testdlls = AddWorkingDirectoryToDLLS(testdlls);
            }
            processInfo.FileName = NCoverConsole;
            processInfo.Arguments = '"' + MSTest + '"' + " ";
            foreach (var dll in testdlls)
            {
                processInfo.Arguments += @"/TestContainer:" + "\"" + dll + "\"" + " ";
            }
            processInfo.Arguments += this.Parmaters;
            return processInfo;
        }

        private IList<string> AddWorkingDirectoryToDLLS(IList<string> testdlls)
        {
            var updatedDlls = new List<string>();
            foreach (var dll in testdlls)
            {
                if (dll.StartsWith(WorkingDirectory))
                {
                    updatedDlls.Add(dll.Remove(0, WorkingDirectory.Length));
                }
            }
            return updatedDlls;
            
        }
    }
}
